//
//  FeedbackEmailSender.m
//  EmailTest
//
//  Created by Blossom on 10-10-16.
//  Copyright 2010 Miles Thorogood, greenmeat.net. All rights reserved.
//

#import "FeedbackEmailSender.h"


extern NSString* kEmailSMTP ;
extern int kEmailPort ;
extern NSString* kEmailFromAddress ;
extern NSString* kEmailFromName ;
extern NSString* kEmailFromPassword ;
extern NSString* kEmailFeedbackEmailSubject ;
extern NSString* kEmailFeedbackEmailHTMLFilepath ;
extern NSString* kEmailFeedbackEmailHTMLImageDir ;
extern NSString* kEmailFeedbackEmailTxtFilepath ;
extern NSString* kEmailDefaultMessage ;
 
 
@implementation FeedbackEmailSender

/* -----------------------------------------------
  Methods
 -------------------------------------------------*/

- (void)sendEmailMessageTo: (NSString *) recipientName AtEmail: (NSString *) recipientEmail {
	
	dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
	
	dispatch_async(queue, ^{
	
		@try {
			//Create the email agent associated with the smtp server that will be used to send emails
			emailAgent = [EDMailAgent  mailAgentForRelayHostWithName:kEmailSMTP port:kEmailPort];
			[emailAgent setUsesSecureConnections:YES]; 
			
			//Set login information
			NSMutableDictionary *authenticationInformation = [NSMutableDictionary dictionary];
			[authenticationInformation setObject:kEmailFromAddress forKey:EDSMTPUserName];
			[authenticationInformation setObject:kEmailFromPassword forKey:EDSMTPPassword];
			[emailAgent setAuthInfo:authenticationInformation];
			
			//Create default message including header
			emailMessage = [self createMessage];
			[emailMessage setSubject:kEmailFeedbackEmailSubject];
			[emailMessage setBody:kEmailFromName forHeaderField:@"From"];
			
			[emailMessage setBody:recipientEmail forHeaderField:@"To"];
			[emailAgent sendMessage:emailMessage];
		}
		@catch (NSException * e) {
			//unsent emails are not recorded
		}
		
	});
}



- (EDInternetMessage *)createMessage
{
    // Create html part
	NSString *html = @"This is the html message.";
	//pathToReadFrom = @"/Users/shared/Kiosk/Email/emailContent.html";
	@try {
		inputEmailMessageFileHandle = [NSFileHandle fileHandleForUpdatingAtPath:kEmailFeedbackEmailHTMLFilepath]; 
		NSData* tempData = [inputEmailMessageFileHandle readDataToEndOfFile];
		html = [[NSString alloc] initWithData:tempData encoding:NSUTF8StringEncoding];
	}
	@catch (NSException * e) {
		//Email file not found using default Jigsaw Kiosk thank you message
		html = kEmailDefaultMessage;		
	}

	EDContentCoder *coder = [[[EDHTMLTextContentCoder alloc] initWithText:html] autorelease];
	EDMessagePart *htmltextPart = [coder messagePart];
	NSMutableArray* htmlPartList = [NSMutableArray arrayWithObjects:htmltextPart, nil];
	
	// Add any embedded images
	NSString* theImageFolder = kEmailFeedbackEmailHTMLImageDir;
	NSString* theCompleteImagePath = nil;
	NSString* theImageName = nil;
	NSDirectoryEnumerator* imagesFolderEnumerator = [[NSFileManager defaultManager]
													 enumeratorAtPath:theImageFolder];
    while((theImageName = [imagesFolderEnumerator nextObject]) != nil) {
		theCompleteImagePath = [NSString stringWithFormat:@"%@/%@", theImageFolder, theImageName];
		NSData *imageData = [NSData dataWithContentsOfFile:theCompleteImagePath];
		if(imageData != nil) {
			coder = [[[EDMultimediaContentCoder alloc] initWithData:imageData filename:theImageName] autorelease];
			EDMessagePart *imagePart = [coder messagePart];
			[imagePart addToHeaderFields:[EDObjectPair pairWithObjects:@"Content-ID":
										  [NSString stringWithFormat:@"<%@>", theImageName]]];
			// Create a related multipart from html part and image part
			[htmlPartList addObject:imagePart];
		}
	} 
	
	EDCompositeContentCoder *compositeCoder = [[[EDCompositeContentCoder alloc] initWithSubparts:htmlPartList] autorelease];
    EDMessagePart *htmlPart = [compositeCoder messagePartWithSubtype:@"related"];
	
    // Create plaintext part
	NSString *plainText = @"This is the plain text alternative.";
	//pathToReadFrom = @"/Users/shared/Kiosk/Email/emailContent.txt";
	@try {
		inputEmailMessageFileHandle = [NSFileHandle fileHandleForUpdatingAtPath:kEmailFeedbackEmailTxtFilepath]; 
		NSData* tempData = [inputEmailMessageFileHandle readDataToEndOfFile];
		plainText = [[NSString alloc] initWithData:tempData encoding:NSUTF8StringEncoding];
	}
	@catch (NSException * e) {
		//Email file not found using default Jigsaw Kiosk thank you message
		plainText = kEmailDefaultMessage;		
	}
	
	coder = [[[EDPlainTextContentCoder alloc] initWithText:plainText] autorelease];
    EDMessagePart *plaintextPart = [coder messagePart];
	
	// Create alternative multipart from plaintext and html parts
	
    NSArray *textPartList = [NSMutableArray arrayWithObjects:plaintextPart, htmlPart, nil];
    compositeCoder = [[[EDCompositeContentCoder alloc] initWithSubparts:textPartList] autorelease];
    EDInternetMessage *message = [compositeCoder messageWithSubtype:@"alternative"];
	
    return message;
}



/* -----------------------------------------------
 Getter and Setter Methods
 -------------------------------------------------*/

@synthesize emailMessage;
@synthesize emailAgent;
@synthesize headerFields;
@synthesize inputEmailMessageFileHandle;


@end
